package shun.demo.remote.display.server;

import android.os.Message;
import android.util.Log;
import shun.demo.remote.display.model.Movement;
import shun.demo.remote.display.model.Point;
import shun.demo.remote.display.model.Property;
import shun.demo.remote.display.model.TimeSync;
import shun.demo.utils.IOUtil;
import shun.demo.utils.Singleton;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;

/**
 * Created by chen on 14-5-9.
 */
public class ReceiveThread extends Thread {

    private Socket mSocket;
    private SendHandler mSendHandler;
    private Clients mClients;

    public ReceiveThread(SendHandler sendHandler, Socket socket) {
        super("Server-ReceiveThread");
        mSendHandler = sendHandler;
        mSocket = socket;
        mClients = Singleton.get(Clients.class);
    }

    @Override
    public void run() {
        InputStream is = null;
        try {
            is = mSocket.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(is);
            while (true) {
                try {
                    Object o = ois.readObject();
                    Log.i(Config.LOG_TAG, "receive " + "\n" + o);
                    if (o instanceof TimeSync) {
                        handleTimeSync((TimeSync) o);
                    } else if (o instanceof Property) {
                        handProperty((Property) o);
                    } else if (o instanceof Point) {
                        handleScreenSync((Point) o);
                    } else if (o instanceof Movement) {
                        handleMovement((Movement)o);
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtil.closeStream(is);
        }
    }

    private void handleMovement(Movement movement) {
        movement.setFrom(mSocket);
        Message message = Message.obtain();
        message.what = SendHandler.MESSAGE_MOVEMENT;
        message.obj = movement;
        mSendHandler.sendMessage(message);

    }

    private void handleScreenSync(Point point) {
        mClients.handScreenSync(point, mSocket);
    }

    private void handProperty(Property p) {
        p.setFrom(mSocket);
        Message message = Message.obtain();
        message.what = SendHandler.MESSAGE_SEND;
        message.obj = p;
        mSendHandler.sendMessage(message);
    }

    private void handleTimeSync(TimeSync timeSync) {
        mClients.handleTimeSync(timeSync, mSocket);
    }
}
